package com.wmx.io.wumengxin.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

/**********************************
 * @author wmx
 * @date 2019/8/28 14:42
 * @description:
 * @version 1.0
 ************************************/
public class HelloNettyServer {
    //私有一个静态内部类
    private static class SingletonWSSever {
        final static HelloNettyServer instance = new HelloNettyServer();
    }

    //公开一个方法获得服务
    public static HelloNettyServer getInstance() {
        return SingletonWSSever.instance;
    }

    private NioEventLoopGroup mainGroup;
    private NioEventLoopGroup subGroup;
    private ServerBootstrap bootstrap;
    private ChannelFuture future;

    private HelloNettyServer() {
        mainGroup = new NioEventLoopGroup(); //定义一个线程池来接入连接
        subGroup = new NioEventLoopGroup(); //处理连接后的任务
        bootstrap = new ServerBootstrap(); // 配置信息
        bootstrap.group(mainGroup, subGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new Handler()); //在每个连接的管道上的last加上自己Handler
                    }
                });
    }

    //服务器开启的方法
    public void start() throws InterruptedException {
        this.future = bootstrap.bind(9999);
        System.err.println("Netty Websocket Server 启动完毕");
    }

    private class Handler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

            System.out.println("server: channel read");
            ByteBuf buf = (ByteBuf) msg;

            System.out.println(buf.toString(CharsetUtil.UTF_8));

            ctx.writeAndFlush(msg);

            ctx.close();

        }

        //负责异常的处理.
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }


}
